package com.mmg.cosplay.utils;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.web.search.WebSearchTool;
import dev.langchain4j.web.search.searchapi.SearchApiWebSearchEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WebSearchEngineTool {

    @Value("${searchapi.apikey}")
    public String searchApiKey;

    /**
     * 联网搜索
     * langchain4j参考文档：https://docs.langchain4j.info/integrations/web-search-engines/searchapi
     * searchapi参数参考文档：https://www.searchapi.io/docs/baidu
     * @param content
     * @return
     */
    @Tool(name = "联网搜索", value = "可以用来搜索互联网以获取最新的信息，回答用户的问题")
    public String search(@P(value = "搜索内容", required = true) String content) {
        log.info("联网搜索内容: {}", content);
        Map<String, Object> optionalParameters = new HashMap<>();
        optionalParameters.put("num", "10");

        SearchApiWebSearchEngine searchEngine = SearchApiWebSearchEngine.builder()
                .apiKey(searchApiKey)
                .engine("baidu")
                .optionalParameters(optionalParameters)
                .build();
        WebSearchTool webTool = WebSearchTool.from(searchEngine);
        return webTool.searchWeb(content);
    }
}
